package com.tonann.app.minio;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.util.Base64;
import java.util.UUID;

@Service
public class MinioService {
    private String endpoint = "http://59.110.170.159:9000" ;

    private String accessKey = "BY9yavzcdzMtgQzTF6LZ";
    private String secretKey ="dreRgjSYo6A4KV4yJTMjtstZ9xJNa8H9LlggjWXO";

    private String bucketName ="threedegree";

    //亚太配置
//    private String endpoint = "http://116.62.132.131:9000" ;
//
//    private String accessKey = "ZHWvlbebnIBW1eHV3b8r";
//    private String secretKey ="q6ldTlrlslr5LFZXSot003xFeMmr7DzirDluyvd8";
//
//    private String bucketName ="threedegree";

    public String uploadBase64Image(String base64Image) throws Exception {
        MinioClient minioClient =  MinioClient.builder().endpoint(endpoint).credentials(accessKey,secretKey).build();
        byte[] data = Base64.getDecoder().decode(base64Image.split(",")[1]);
        String objectName = UUID.randomUUID().toString();
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(new ByteArrayInputStream(data), data.length, -1)
                .contentType("image/jpeg")
                .build();
        minioClient.putObject(putObjectArgs);
        return objectName;
    }
    public String uploadBufferImage(BufferedImage image) throws Exception {
        String objectName = UUID.randomUUID().toString() + ".jpg";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        byte[] imageBytes = outputStream.toByteArray();
        MinioClient minioClient =  MinioClient.builder().endpoint(endpoint).credentials(accessKey,secretKey).build();
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(new ByteArrayInputStream(imageBytes), imageBytes.length, -1)
                .contentType("image/jpeg")
                .build();
        minioClient.putObject(putObjectArgs);

        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    }
}
